var $, tab, layer;
window.model = {};
window.sysMenu = {};
window.metadata = {};
window.sysUser = {};
layui.config({
    base: "js/"
}).extend({
    "bodyTab": "bodyTab"
});
layui.use(['bodyTab', 'form', 'element', 'layer', 'jquery'], function () {
    var form = layui.form,
        element = layui.element;
    $ = layui.$;
    layer = parent.layer === undefined ? layui.layer : top.layer;
    tab = layui.bodyTab({
        openTabNum: "50" //最大可打开窗口数量
    });
    if (layuiFunciton.requestType) {
        //获取登录用户
        layuiFunciton.ajaxRequest({
            url: layuiFunciton.URL + '/sign/getCurrentUserInfo',
            method: 'get',
            success: function (data) {
                if (data == null) {
                    window.location.href = "/page/login/login.html"
                } else {
                    window.sysUser = data;
                    //用户姓名
                    $(".adminName").text(data.name);
                    //用户图像
                    $("#userInfo").find("img").attr("src", data.employeeHead);
                    /*唯一登录*/
                    //layuiFunciton.webSocket(data.UUID);
                    //是否锁屏
                    if (data.lockScreen == 1) {
                        lockPage(data.account, data.employeeHead);
                    }
                }
            }
        });
    }
    //获取菜单
    layuiFunciton.ajaxRequest({
        url: layuiFunciton.requestType ? layuiFunciton.URL + "/sysAuthority/querySysMenu" : "json/querySysMenu.json",
        method: "get",
        data: {},
        success: function (returnDate) {
            if (returnDate.length <= 0) {
                layuiFunciton.warn("无权限！");
            }
            getMoble(returnDate);
            var dlTopLevelMenus = '', topLevelMenus = '';
            $.each(eval(returnDate), function (index, value, array) {
                window.model[value.id] = value.children;
                if (index == 0) {
                    //重新渲染左侧菜单
                    tab.render(value.children);
                    dlTopLevelMenus += '<dd class="layui-this" data-sysMenu="' + value.id + '"><a href="javascript:;"><cite>' + value.menuName + '</cite></a></dd>';
                    topLevelMenus += '<li class="layui-nav-item layui-this" data-sysMenu="' + value.id + '"><a href="javascript:;"><cite>' + value.menuName + '</cite></a></li>';
                } else {
                    dlTopLevelMenus += '<dd data-sysMenu="' + value.id + '"><a href="javascript:;"><cite>' + value.menuName + '</cite></a></dd>';
                    topLevelMenus += ' <li class="layui-nav-item" data-sysMenu="' + value.id + '" pc><a href="javascript:;"><cite>' + value.menuName + '</cite></a></li>';
                }
            });
            //$("#topLevelMenus").html(topLevelMenus);
            //$("#dlTopLevelMenus").html(dlTopLevelMenus);
            //页面加载时判断左侧菜单是否显示
            //通过顶部菜单获取左侧菜单
            $("#topLevelMenus li,#dlTopLevelMenus dd").click(function () {
                //if ($(this).parents(".mobileTopLevelMenus").length != "0") {
                $(".topLevelMenus li").eq($(this).index()).addClass("layui-this").siblings().removeClass("layui-this");
                //} else {
                $(".mobileTopLevelMenus dd").eq($(this).index()).addClass("layui-this").siblings().removeClass("layui-this");
                //}
                $(".layui-layout-admin").removeClass("showMenu");
                $("body").addClass("site-mobile");
                var meneId = $(this).attr("data-sysMenu");
                //加载左边菜单
                tab.render(window.model[meneId]);
                //渲染顶部窗口
                tab.tabMove();
            });
        }
    });
    function getMoble(returnDate) {
        $.each(eval(returnDate), function (index, value, array) {
            window.sysMenu[value.id] = value;
            if (value.sysMetadataList.length > 0) {
                window.metadata[value.id] = value.sysMetadataList;
            }
            if (value.children.length > 0) {
                getMoble(value.children)
            }
        });
    }

    //隐藏左侧导航
    $(".hideMenu").click(function () {
        if ($(".topLevelMenus li.layui-this a").data("url")) {
            layer.msg("此栏目状态下左侧菜单不可展开"); //主要为了避免左侧显示的内容与顶部菜单不匹配
            return false;
        }
        $(".layui-layout-admin").toggleClass("showMenu");
        //渲染顶部窗口
        tab.tabMove();
    });

    //手机设备的简单适配
    $('.site-tree-mobile').on('click', function () {
        $('body').addClass('site-mobile');
    });
    $('.site-mobile-shade').on('click', function () {
        $('body').removeClass('site-mobile');
    });

    // 添加新窗口
    $("body").on("click", ".layui-nav .layui-nav-item a:not('.mobileTopLevelMenus .layui-nav-item a')", function () {
        //如果不存在子级
        if ($(this).siblings().length == 0) {
            addTab($(this));
            $('body').removeClass('site-mobile'); //移动端点击菜单关闭菜单层
        }
        $(this).parent("li").siblings().removeClass("layui-nav-itemed");
    });

    //清除缓存
    $(".clearCache").click(function () {
        window.sessionStorage.clear();
        window.localStorage.clear();
        var index = layer.msg('清除缓存中，请稍候', {icon: 16, time: false, shade: 0.8});
        setTimeout(function () {
            layer.close(index);
            layer.msg("缓存清除成功！");
        }, 1000);
    });

    //刷新后还原打开的窗口
    if (window.sysUser.tabCache == 1) {
        if (window.sessionStorage.getItem("menu") != null) {
            menu = JSON.parse(window.sessionStorage.getItem("menu"));
            curmenu = window.sessionStorage.getItem("curmenu");
            var openTitle = '';
            for (var i = 0; i < menu.length; i++) {
                openTitle = '';
                if (menu[i].icon) {
                    if (menu[i].icon.split("-")[0] == 'icon') {
                        openTitle += '<i class="seraph ' + menu[i].icon + '"></i>';
                    } else {
                        openTitle += '<i class="layui-icon">' + menu[i].icon + '</i>';
                    }
                }
                openTitle += '<cite>' + menu[i].title + '<input type="hidden" value="' + menu[i].menuId + '"></cite>';
                openTitle += '<i class="layui-icon layui-unselect layui-tab-close" data-id="' + menu[i].layId + '">&#x1006;</i>';
                element.tabAdd("bodyTab", {
                    title: openTitle,
                    content: "<iframe src='" + menu[i].href + "' data-id='" + menu[i].layId + "'></frame>",
                    id: menu[i].layId
                });
                //定位到刷新前的窗口
                if (curmenu != "undefined") {
                    if (curmenu == '' || curmenu == "null") { //定位到后台首页
                        element.tabChange("bodyTab", '');
                    } else if (JSON.parse(curmenu).title == menu[i].title) { //定位到刷新前的页面
                        window.currentMenuId = menu[i].menuId;
                        element.tabChange("bodyTab", menu[i].layId);
                    }
                } else {
                    element.tabChange("bodyTab", menu[menu.length - 1].layId);
                }
            }
            //渲染顶部窗口
            tab.tabMove();
        }
    } else {
        window.sessionStorage.removeItem("menu");
        window.sessionStorage.removeItem("curmenu");
    }

    //功能设定
    $(".functionSetting").click(function () {
        layer.open({
            title: "功能设定",
            area: ["380px", "280px"],
            type: "1",
            content: '<div class="functionSrtting_box">' +
            '<form class="layui-form">' +
            '<div class="layui-form-item">' +
            '<label class="layui-form-label">开启Tab缓存</label>' +
            '<div class="layui-input-block">' +
            '<input type="checkbox" name="cache" lay-skin="switch" lay-text="开|关">' +
            '<div class="layui-word-aux">开启后刷新页面不关闭打开的Tab页</div>' +
            '</div>' +
            '</div>' +
            '<div class="layui-form-item">' +
            '<label class="layui-form-label">Tab切换刷新</label>' +
            '<div class="layui-input-block">' +
            '<input type="checkbox" name="changeRefresh" lay-skin="switch" lay-text="开|关">' +
            '<div class="layui-word-aux">开启后切换窗口刷新当前页面</div>' +
            '</div>' +
            '</div>' +
            '<div class="layui-form-item">' +
            '<label class="layui-form-label">单一登陆</label>' +
            '<div class="layui-input-block">' +
            '<input type="checkbox" name="oneLogin" lay-filter="multipleLogin" lay-skin="switch" lay-text="是|否">' +
            '<div class="layui-word-aux">开启后不可同时多个地方登录</div>' +
            '</div>' +
            '</div>' +
            '<div class="layui-form-item skinBtn">' +
            '<a href="javascript:;" class="layui-btn layui-btn-sm layui-btn-normal" lay-submit="" lay-filter="settingSuccess">设定完成</a>' +
            '<a href="javascript:;" class="layui-btn layui-btn-sm layui-btn-primary" lay-submit="" lay-filter="noSetting">朕再想想</a>' +
            '</div>' +
            '</form>' +
            '</div>',
            success: function (index, layero) {
                //如果之前设置过，则设置它的值
                $(".functionSrtting_box input[name=cache]").prop("checked", window.sysUser.tabCache == 1 ? true : false);
                $(".functionSrtting_box input[name=changeRefresh]").prop("checked", window.sysUser.tabRefresh == 1 ? true : false);
                $(".functionSrtting_box input[name=oneLogin]").prop("checked", window.sysUser.aSingleLogin == 1 ? true : false);
                //设定
                form.on("submit(settingSuccess)", function (data) {
                    window.sessionStorage.setItem("cache", data.field.cache == "on" ? "true" : "false");
                    window.sessionStorage.setItem("changeRefresh", data.field.changeRefresh == "on" ? "true" : "false");
                    window.sessionStorage.setItem("oneLogin", data.field.oneLogin == "on" ? "true" : "false");
                    window.sessionStorage.removeItem("menu");
                    window.sessionStorage.removeItem("curmenu");
                    layuiFunciton.ajaxRequest({
                        url: layuiFunciton.URL + '/sysUser/updateSysUserInfo',
                        method: 'post',
                        data: {
                            tabCache: data.field.cache == "on" ? 1 : 0,
                            tabRefresh: data.field.changeRefresh == "on" ? 1 : 0,
                            aSingleLogin: data.field.oneLogin == "on" ? 1 : 0
                        },
                        success: function (data) {

                        }
                    });
                    location.reload();
                    return false;
                });
                //取消设定
                form.on("submit(noSetting)", function () {
                    layer.closeAll("page");
                });
                //单一登陆提示
                form.on('switch(multipleLogin)', function (data) {
                    layer.tips('温馨提示：此功能需重新登录', data.othis, {tips: 1})
                });
                form.render();  //表单渲染
            }
        })
    });
    // 解锁
    $("body").on("click", "#unlock", function () {
        if ($(this).siblings(".admin-header-lock-input").val() == '') {
            layer.msg("请输入解锁密码！");
            $(this).siblings(".admin-header-lock-input").focus();
        } else {
            layuiFunciton.ajaxRequest({
                url: layuiFunciton.URL + '/sysUser/unlock',
                method: 'post',
                data: {password: $(this).siblings(".admin-header-lock-input").val()},
                success: function (data) {
                    if (data > 0) {
                        $(this).siblings(".admin-header-lock-input").val('');
                        layer.closeAll("page");
                    } else {
                        layer.msg("密码错误，请重新输入！");
                        $(this).siblings(".admin-header-lock-input").val('').focus();
                    }
                }
            });
        }
    });

});

//打开新窗口
function addTab(_this) {
    tab.tabAdd(_this);
}
//图片管理弹窗
function showImg() {
    $.getJSON('json/images.json', function (json) {
        var res = json;
        layer.photos({
            photos: res,
            anim: 5
        });
    });
}
//注销
function signOut() {
    layuiFunciton.ajaxRequest({
        url: layuiFunciton.URL + '/sign/logout',
        method: 'get',
        success: function (data) {
            window.location.href = "/page/login/login.html";
        }
    });
}

//锁屏
function lockPage() {
    layuiFunciton.ajaxRequest({
        url: layuiFunciton.URL + '/sysUser/updateSysUserInfo',
        method: 'post',
        data: {
            lockScreen: 1
        },
        success: function (data) {

        }
    });
    layer.open({
        title: false,
        type: 1,
        content: '<div class="admin-header-lock" id="lock-box">' +
        '<div class="admin-header-lock-img"><img src="' + window.sysUser.employeeHead + '" class="userAvatar"/></div>' +
        '<div class="admin-header-lock-name" id="lockUserName">' + window.sysUser.account + '</div>' +
        '<div class="input_btn">' +
        '<input type="password" class="admin-header-lock-input layui-input" autocomplete="off" placeholder="请输入密码解锁.." name="lockPwd" id="lockPwd" />' +
        '<button class="layui-btn" id="unlock">解锁</button>' +
        '</div>' +
        '<p>请输入用户密码，否则不会解锁成功哦！！！</p>' +
        '</div>',
        closeBtn: 0,
        shade: 0.9,
        success: function () {
        }
    });
    $(".admin-header-lock-input").focus();
}
